/**
 * 
 */
package com.zhonggong.tools;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Administrator
 *
 */
public class DBUtil {
	

	private final static String DRIVER_CLASS ="com.mysql.jdbc.Driver"; 

	private final static String URL = "jdbc:mysql://127.0.0.1:3306/zbh?characterEncoding=utf8";
	private final static String USER = "root";
	private final static String PWD = "root";

	private static Connection connection;
	private static PreparedStatement pStatement;
	private static ResultSet rSet;
	
	static {
		try {
			Class.forName(DRIVER_CLASS);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	public static Connection getConn() throws ClassNotFoundException, SQLException {
		
		connection = DriverManager.getConnection(URL,USER, PWD);
		return connection;
	}

	public static void close() throws SQLException {
		if (rSet != null) {
			rSet.close();
		}
		
		if (pStatement != null) {
			pStatement.close();
		}
		if (connection != null) {
			connection.close();
		}
	}

	
	public static ResultSet query(String sql,Object[] objects) throws ClassNotFoundException, SQLException {
		connection = getConn();
		
		pStatement = connection.prepareStatement(sql);
		
		for (int i = 0; i < objects.length; i++) {
			pStatement.setObject(i+1, objects[i]);
		}
		
		rSet = pStatement.executeQuery();
		return rSet;
	}
	
	public static int update(String sql,Object[] objects) throws ClassNotFoundException, SQLException {

		connection = getConn();

		pStatement = connection.prepareStatement(sql);

		for (int i = 0; i < objects.length; i++) {
			pStatement.setObject(i+1, objects[i]);
		}

		return pStatement.executeUpdate();		
	}
}
